package com.example.springboot.service;

import cn.hutool.core.util.StrUtil;
import com.example.springboot.common.TokenUtils;
import com.example.springboot.entity.Account;
import com.example.springboot.entity.Admin;
import com.example.springboot.exception.CustomerException;
import com.example.springboot.mapper.AdminMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminService {

    @Resource
    AdminMapper adminMapper;

    public Admin login(Account account) {
        // 查询用户名是否存在
        Admin dbAdmin = adminMapper.selectByUsername(account.getUsername());
        if (dbAdmin == null){
            throw new CustomerException("用户名不存在");
        }
        // 密码是否正确
        if (!dbAdmin.getPassword().equals(account.getPassword())){
            throw new CustomerException("账号或密码错误");
        }
        return dbAdmin;
    }

    public PageInfo<Admin> selectPage(Integer pageNum, Integer pageSize, Admin admin) {
        //开启分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<Admin> adminsList = adminMapper.selectAll(admin);
        return PageInfo.of(adminsList);
    }

    public void add(Admin admin) {
        Admin dbAdmin = adminMapper.selectByUsername(admin.getUsername());
        if (dbAdmin != null){
            throw new CustomerException("用户名已存在");
        }
        //默认密码
        if (StrUtil.isBlank(admin.getPassword())){
            admin.setPassword("admin");
        }
        admin.setRole("ADMIN");
        adminMapper.insert(admin);
    }

    public void update(Admin admin) {
        adminMapper.updateById(admin);
    }

    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    public void deleteBatch(List<Admin> adminList) {
        for (Admin admin : adminList) {
            this.deleteById(admin.getId());
        }
    }

    public void updatePassword(Admin admin) {
        // 先判断一下用户输入的新密码和确认密码是否一致
        if (!admin.getNewPassword().equals(admin.getConfirmPassword())){
            throw new CustomerException("500","新密码和确认密码不一致");
        }
        if (!admin.getPassword().equals(admin.getPassword())){
            throw new CustomerException("500","原密码输入错误");
        }
        // 密码正确，修改密码
        Admin dbAdmin = adminMapper.selectById(admin.getId().toString());
        admin.setPassword(admin.getNewPassword());
        adminMapper.updateById(admin);
    }

    public Account selectById(String userId) {
        return adminMapper.selectById(userId);
    }
}
